import useFetchData from '@ant-design/pro-descriptions/es/useFetchData';
import SfwLoadingContainer from '@sfkj/sfw-dc-ui/common/SfwLoadingContainer';
import { Empty, Image, ModalProps, Typography } from 'antd';
import lodash from 'lodash';
import React, { useMemo } from 'react';
import { cqrs } from '../../utils';

export type UploadFileType = {
  url: string;
  name: string;
  size: number;
  type: string;
};

export type SfwFilePreviewContentProps = {
  file?: UploadFileType;
} & ModalProps;

const getSuffix = (filename: string) => {
  return filename.slice(filename.lastIndexOf('.'));
};

// Word文档：'.doc','.docx','.wps','.wpss','.docm','.dotm','.dot','.dotx','.html'
// PPT文档：'.pptx','.ppt','.pot','.potx','.pps','.ppsx','.dps','.dpt','.pptm','.potm','.ppsm','.dpss'
// Excel文档：'.xls','.xlt','.et','.ett','.xlsx','.xltx','.csv','.xlsb','.xlsm','.xltm','.ets'
// PDF文档：'.pdf','.txt'
// 音频文件：'.avi','.mpeg','.mpg','.dat','.divx','.xvid','.rm','.rmvb','.mov','.qt','.asf','.wmv','.vob','.3gp','.mp4','.flv','.avs','.mkv','.ts','.ogm','.nsv','.swf','.mxf'
// 视频文件：'.wav','.pcm','.tta','.flac','.au','.ape','.mp3','.wma','.ogg','.aac','.ra','.midi','.mpc','.mv','.aif','.aiff','.m4a','.mka','.mp2','.mpa','.wv','.ac3','.dts','.amr','.3gpp','.oga','.opus'

const wordTypes = [
  '.doc',
  '.docx',
  '.wps',
  '.wpss',
  '.docm',
  '.dotm',
  '.dot',
  '.dotx',
  '.html',
];
const pptTypes = [
  '.pptx',
  '.ppt',
  '.pot',
  '.potx',
  '.pps',
  '.ppsx',
  '.dps',
  '.dpt',
  '.pptm',
  '.potm',
  '.ppsm',
  '.dpss',
];
const excelTypes = [
  '.xls',
  '.xlt',
  '.et',
  '.ett',
  '.xlsx',
  '.xltx',
  '.csv',
  '.xlsb',
  '.xlsm',
  '.xltm',
  '.ets',
];
const pdfTypes = ['.txt', '.pdf'];
const allWordTypes = [...wordTypes, pptTypes, ...excelTypes, ...pdfTypes];
const imageTypes = [
  '.gif',
  '.png',
  '.apng',
  '.jpg',
  '.jpeg',
  '.bmp',
  '.ico',
  '.svg',
  '.tif',
  '.tiff',
  '.webp',
];
const videoTypes = [
  '.avi',
  '.mpeg',
  '.mpg',
  '.dat',
  '.divx',
  '.xvid',
  '.rm',
  '.rmvb',
  '.mov',
  '.qt',
  '.asf',
  '.wmv',
  '.vob',
  '.3gp',
  '.mp4',
  '.flv',
  '.avs',
  '.mkv',
  '.ts',
  '.ogm',
  '.nsv',
  '.swf',
  '.mxf',
];
const audioTypes = [
  '.wav',
  '.pcm',
  '.tta',
  '.flac',
  '.au',
  '.ape',
  '.mp3',
  '.wma',
  '.ogg',
  '.aac',
  '.ra',
  '.midi',
  '.mpc',
  '.mv',
  '.aif',
  '.aiff',
  '.m4a',
  '.mka',
  '.mp2',
  '.mpa',
  '.wv',
  '.ac3',
  '.dts',
  '.amr',
  '.3gpp',
  '.oga',
  '.opus',
];
const videoAndAudioTypes = [...videoTypes, audioTypes];

const getFileType = (filename: string) => {
  const suffix = getSuffix(filename);

  if (lodash.includes(allWordTypes, suffix)) {
    return 1;
  } else if (lodash.includes(imageTypes, suffix)) {
    return 2;
  } else if (lodash.includes(videoAndAudioTypes, suffix)) {
    return 3;
  }
  return 4;
};

const SfwFilePreviewContentImm: React.FC<SfwFilePreviewContentProps> = (
  props,
) => {
  const { file, ...rest } = props;
  const [error, setError] = React.useState<any>();
  const fetchData = useMemo(() => {
    return async () => {
      const result = await cqrs.queryForForm({
        body: {
          code: 'OssSignatureUrlQry',
          params: {
            data: {
              path: file?.url,
            },
          },
        },
      });
      return {
        data: result,
      };
    };
  }, [file]);
  const action = useFetchData<any>(fetchData, {
    manual: false,
    effects: [file],
    onRequestError: (e) => setError(e),
  });
  const { loading, dataSource } = action;
  const queryResult = {
    loading,
    data: dataSource,
    error: error,
  };
  console.log(queryResult);

  return (
    <SfwLoadingContainer queryResult={queryResult}>
      <iframe
        src={queryResult?.data?.url as string}
        width="100%"
        height="100%"
        style={{
          border: 0,
        }}
        title="文件预览"
        {...(rest as any)}
      />
    </SfwLoadingContainer>
  );
};

const SfwFilePreviewContent: React.FC<SfwFilePreviewContentProps> = (props) => {
  const { file, ...restProps } = props;

  if (lodash.isEmpty(file)) {
    return (
      <Empty
        description={
          <>
            <Typography.Title level={5}>文件不存在</Typography.Title>
            <Typography.Text>没有可预览的文件</Typography.Text>
          </>
        }
      />
    );
  }

  const type = getFileType(file.name);
  const contentDom = (type: number) => {
    // 文档
    if (type === 1) {
      return <SfwFilePreviewContentImm {...props} />;
    }
    if (type === 2) {
      return (
        <div
          style={{
            position: 'relative',
            width: '100%',
            height: '100%',
          }}
        >
          <Image
            wrapperStyle={{
              width: '100%',
              height: '100%',
            }}
            style={{
              position: 'static',
              display: 'block',
              width: '100%',
              height: '100%',
              objectFit: 'contain',
            }}
            src={file.url}
            placeholder={
              <Image
                preview={false}
                src={`${file.url}?x-oss-process=image/blur,r_50,s_50/quality,q_1/resize,m_mfit,h_200,w_200`}
              />
            }
            preview={false}
            {...(restProps as any)}
          />
        </div>
      );
    }
    if (type === 3) {
      return (
        <video
          style={{
            width: '100%',
          }}
          muted
          controls
          src={file.url}
          {...(restProps as any)}
        />
      );
    }
    return `文件不支持预览：${file.url}`;
  };

  return <>{contentDom(type)}</>;
};

export default SfwFilePreviewContent;
